import requests
import json
from typing import Dict, List, Optional
from datetime import datetime, timedelta
import time

class TrainAPI:
    def __init__(self):
        self.base_url = "https://kyfw.12306.cn/otn"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9',
        }
        
    # 下面保留原模拟接口...
    def get_stations(self) -> Dict[str, str]:
        return {}
    
    def search_trains(self, from_station: str, to_station: str, 
                     date: str = None) -> List[Dict]:
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        return self._get_mock_train_data(from_station, to_station, date)
    
    def _get_mock_train_data(self, from_station: str, to_station: str, date: str) -> List[Dict]:
        mock_trains = [
            {
                'train_no': 'G1',
                'train_type': '高铁',
                'from_station': from_station,
                'to_station': to_station,
                'departure_time': '06:00',
                'arrival_time': '11:30',
                'duration': '5小时30分',
                'price': {
                    'business': 1748,
                    'first': 924,
                    'second': 553
                },
                'seats': {
                    'business': '有',
                    'first': '有',
                    'second': '有'
                },
                'date': date
            }
        ]
        return mock_trains
    
    def get_train_schedule(self, train_no: str, date: str) -> List[Dict]:
        return []
    
    def get_ticket_price(self, train_no: str, from_station: str, 
                        to_station: str, seat_type: str) -> Dict:
        return 0

class TrainJuheClient:
    """聚合数据 - 火车订票查询（ID:817）简单适配器"""
    def __init__(self, appkey: str):
        self.appkey = appkey
        # 根据你提供的示例，走 fapigw 统一网关
        self.endpoint = "https://apis.juhe.cn/fapigw/train/query"
        self.session = requests.Session()
    
    def query(self, from_city: str, to_city: str, date: str) -> List[Dict]:
        """按城市/站名查询车次列表，返回兼容 simple_http_server 的结构"""
        try:
            # search_type 文档支持站名/站码，这里用站名
            params = {
                'key': self.appkey,
                'search_type': 'name',
                'departure_station': from_city,
                'arrival_station': to_city,
                'date': date or datetime.now().strftime('%Y-%m-%d'),
                'filter': '',
                'enable_booking': '',
                'departure_time_range': ''
            }
            r = self.session.get(self.endpoint, params=params, timeout=10)
            data = r.json()
            # 聚合的网关一般返回 result/list 或 data
            if data.get('error_code') == 0 and data.get('result'):
                result = data['result']
                # 可能是 list
                items = result if isinstance(result, list) else result.get('list') or []
                trains = []
                for item in items[:5]:
                    # 获取价格信息（取最低价）
                    prices = item.get('prices', [])
                    min_price = 0
                    if prices:
                        min_price = min([p.get('price', 0) for p in prices if p.get('price', 0) > 0])
                    
                    trains.append({
                        'type': 'high_speed_rail' if str(item.get('train_no') or item.get('train_code','')).startswith(('G','D')) else 'train',
                        'train_number': item.get('train_no') or item.get('train_code') or '',
                        'departure_time': item.get('departure_time') or item.get('start_time',''),
                        'arrival_time': item.get('arrival_time') or item.get('arrive_time',''),
                        'duration': item.get('duration') or item.get('run_time',''),
                        'price': min_price,
                        'seats_available': '有' if item.get('enable_booking') == 'Y' else '无',
                        'origin': item.get('departure_station') or item.get('from_station_name', from_city),
                        'destination': item.get('arrival_station') or item.get('to_station_name', to_city)
                    })
                return trains
        except Exception as e:
            print(f"聚合数据查询失败: {e}")
        return []

class FlightJuheClient:
    """聚合数据 - 航班查询（ID:818）适配器"""
    def __init__(self, appkey: str, max_segments: int = 0):
        self.appkey = appkey
        self.max_segments = max_segments
        self.endpoint = "https://apis.juhe.cn/flight/query"
        self.session = requests.Session()
    
    def query(self, departure_code: str, arrival_code: str, date: str, flight_no: str = "") -> List[Dict]:
        """用 IATA 城市/机场三字码查询航班; 返回统一结构，含 segments"""
        try:
            params = {
                'key': self.appkey,
                'departure': departure_code,
                'arrival': arrival_code,
                'departureDate': date,
                'maxSegments': str(self.max_segments)
            }
            if flight_no:
                params['flightNo'] = flight_no
            r = self.session.get(self.endpoint, params=params, timeout=10)
            data = r.json()
            flights: List[Dict] = []
            if data.get('error_code') == 0 and data.get('result') and data['result'].get('flightInfo'):
                for item in data['result']['flightInfo'][:10]:
                    flights.append({
                        'type': 'flight',
                        'flight_number': item.get('flightNo', ''),
                        'airline': item.get('airlineName') or item.get('airline', ''),
                        'origin': item.get('departureName') or item.get('departure'),
                        'destination': item.get('arrivalName') or item.get('arrival'),
                        'departure_time': f"{item.get('departureDate','')} {item.get('departureTime','')}",
                        'arrival_time': f"{item.get('arrivalDate','')} {item.get('arrivalTime','')}",
                        'duration': item.get('duration', ''),
                        'price': item.get('ticketPrice') or 0,
                        'segments': item.get('segments') or []
                    })
            return flights
        except Exception as e:
            print(f"聚合航班查询失败: {e}")
            return [] 